package com.soft.mainsite.module.sensitiveword.service;

import com.soft.mainsite.common.domain.ErrorCode;
import com.soft.mainsite.common.exception.CmsException;
import com.soft.mainsite.common.utils.JsonUtil;
import com.soft.mainsite.module.sensitiveword.dao.SensitiveWordDao;
import com.soft.mainsite.module.sensitiveword.dto.SensitiveWordDto;
import com.soft.mainsite.module.sensitiveword.dto.SensitiveWordQueryParams;
import com.soft.mainsite.module.sensitiveword.entity.SensitiveWord;
import com.soft.mainsite.module.sensitiveword.utils.SensitiveWordUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * SensitiveWordServiceImpl.java 此类用于敏感词业务层
 *
 * @author:李昭阳
 * @date:2019/4/11 0011
 * @remark:
 */
@Slf4j
@Component
public class SensitiveWordServiceImpl implements SensitiveWordService{

    @Autowired
    private SensitiveWordDao sensitiveWordDao;

    /**
     * 只读事务标识，读写分离
     * @param queryParams
     * @return
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    @Override
    public List<SensitiveWordDto> getSensitiveWordByConditions(SensitiveWordQueryParams queryParams) {
        List<SensitiveWord> sensitiveWords = sensitiveWordDao.selectSensitiveWordByConditions(queryParams);
        List<SensitiveWordDto> sensitiveWordDtos = SensitiveWordDto.convertEntityToDtos(sensitiveWords);
        return sensitiveWordDtos;
    }

    @Override
    public String save(String[] wordContents) {
        if(ArrayUtils.isEmpty(wordContents)){
            log.error("添加敏感词失败，添加数据为" + wordContents);
            return JsonUtil.toError(ErrorCode.E_100201.getCode());
        }
        int i = sensitiveWordDao.insertSensitiveWord(wordContents);
        if(i > 0){
            return JsonUtil.toSuccess("操作成功","sensitive-word-tab",false);
        }
        return  JsonUtil.toError("操作失败");
    }

    @Override
    public String permit(Long[] ids) {
        int i = sensitiveWordDao.permitSensitiveWord(ids);
        if(i > 0){
            return JsonUtil.toSuccess("操作成功","sensitive-word-tab",false);
        }
        return  JsonUtil.toError("操作失败");
    }

    @Override
    public String delete(Long[] ids) {
        int i = sensitiveWordDao.deleteSensitiveWord(ids);
        if(i > 0){
            return JsonUtil.toSuccess("操作成功","sensitive-word-tab",false);
        }
        return  JsonUtil.toError("操作失败");
    }

    @Override
    public String checkSensitiveWord(String content) {
        long startNumer = System.currentTimeMillis();
        String replceStr = "*";
        int replceSize = 500;

        //初始化
        StringBuilder replaceAll = new StringBuilder(replceSize);
        for(int x=0;x < replceSize;x++)
        {
            replaceAll.append(replceStr);
        }
        // 加载词库
        List<String> arrayList = new ArrayList<String>();
        // TODO 先从缓存 （未做缓存）

        // 数据库中
        SensitiveWordQueryParams queryParams = new SensitiveWordQueryParams();
        // 取出使用中的敏感词 状态为1
        queryParams.setWordStatus(1);
        List<SensitiveWordDto> sensitiveWordByConditions = this.getSensitiveWordByConditions(queryParams);
        for(SensitiveWordDto sensitiveWordDto : sensitiveWordByConditions){
            if(!arrayList.contains(sensitiveWordDto.getWordContent())) {
                arrayList.add(sensitiveWordDto.getWordContent());
            }
        }
        SensitiveWordUtils sw = new SensitiveWordUtils(replaceAll, arrayList);
        content = sw.filterInfo(content);

        log.info("敏感词：" + sw.getArrayList());
        log.info("敏感词的数量：" + sw.getArrayList().size());
        log.info("语句中包含敏感词的个数为：" + sw.sensitiveWordList.size() + "。包含：" + sw.sensitiveWordSet);
        log.info("替换后的字符串为:\n" + content);
        long endNumber = System.currentTimeMillis();
        log.info("总共耗时:"+(endNumber-startNumer)+"ms");

        // 抛出异常
        if(sw.sensitiveWordList.size() > 0){
            log.info("语句中包含敏感词的个数为：" + sw.sensitiveWordList.size() + "。包含：" + sw.sensitiveWordSet);
            throw new CmsException(ErrorCode.E_100202.getDesc() + sw.sensitiveWordSet);
        }

        // 返回替换内容
        return content;
    }


}
